package com.zjeav.lingjiao.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dalimao.corelibrary.view.HorizontalListView;
import com.google.gson.JsonSyntaxException;
import com.jpeng.jptabbar.JPTabBar;
import com.maning.mndialoglibrary.MProgressDialog;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;
import com.zjeav.lingjiao.R;
import com.zjeav.lingjiao.base.adapter.BookAdapter;
import com.zjeav.lingjiao.base.adapter.HorizontalAdapter;
import com.zjeav.lingjiao.base.baseBean.BaseFragment;
import com.zjeav.lingjiao.base.baseBean.Book;
import com.zjeav.lingjiao.base.baseBean.Extra;
import com.zjeav.lingjiao.base.baseBean.Province;
import com.zjeav.lingjiao.base.baseBean.Result;
import com.zjeav.lingjiao.base.request.BookRequest;
import com.zjeav.lingjiao.base.request.GetVersionRequest;
import com.zjeav.lingjiao.base.request.MallBookRequest;
import com.zjeav.lingjiao.base.response.BannerResponse;
import com.zjeav.lingjiao.base.response.SubjectResponse;
import com.zjeav.lingjiao.base.response.SysSetting;
import com.zjeav.lingjiao.base.response.VersionResponse;
import com.zjeav.lingjiao.base.tools.GlideImageLoader;
import com.zjeav.lingjiao.base.tools.SharedPreferencesUtils;
import com.zjeav.lingjiao.base.utils.DetectionUpdate;
import com.zjeav.lingjiao.base.utils.ErrorUtils;
import com.zjeav.lingjiao.base.utils.StringUtils;
import com.zjeav.lingjiao.base.utils.UIUtils;
import com.zjeav.lingjiao.ui.book.BookDetialActivity;
import com.zjeav.lingjiao.ui.book.BookMarketActivity;
import com.zjeav.lingjiao.ui.book.MallBookContract;
import com.zjeav.lingjiao.ui.book.SaoMiaoBookActivity;
import com.zjeav.lingjiao.ui.home.Find.FindwebViewActivity;
import com.zjeav.lingjiao.ui.home.persenter.GetVersionPersenter;
import com.zjeav.lingjiao.ui.home.persenter.MainPersenter;
import com.zjeav.lingjiao.ui.home.persenter.SyssetPersenter;
import com.zjeav.lingjiao.ui.home.view.GetVersionContract;
import com.zjeav.lingjiao.ui.home.view.HomeContract;
import com.zjeav.lingjiao.ui.home.view.SyssetContract;
import com.zjeav.lingjiao.ui.presenter.BookPresenter;

import java.util.ArrayList;
import java.util.Arrays;

import static android.app.Activity.RESULT_OK;

/**
 *
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener,
        TextWatcher, HomeContract.View,MallBookContract.View,SyssetContract.View,
        GetVersionContract.View{

    private JPTabBar mTabBar;
    private MainPersenter mainPersenter;
    private HorizontalListView mHorizontalListView;
    private HorizontalAdapter mAdapter;
    ArrayList<SubjectResponse> subjects = new ArrayList<>();

    Banner banner;
    ImageView saomiao_img;
    RecyclerView recyclerView;
    RefreshLayout refreshLayout;
    BookPresenter bookPresenter;
    BookAdapter adapter;
    GetVersionPersenter getVersionPersenter;
    SyssetPersenter syssetPersenter;
    boolean mallmode;
    private int REQUEST_CODE_SCAN = 111;
    ArrayList<Book> books = new ArrayList<>();
    int index = 1;
    int size = 10;
    Intent intent;
    ArrayList<BannerResponse> bannerResponses = new ArrayList<>();


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.home, null);
        init(layout);
        return layout;
    }

    private void init(View layout) {
        mTabBar = ((RestructureMainActivity) getActivity()).getTabbar();
        recyclerView = layout.findViewById(R.id.recyclerView);
        refreshLayout = layout.findViewById(R.id.refreshLayout);
        saomiao_img = layout.findViewById(R.id.saomiao_img);
        saomiao_img.setOnClickListener(this);
        adapter = new BookAdapter(getContext());
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
        recyclerView.setAdapter(adapter);
        mainPersenter = new MainPersenter(this);
        banner = layout.findViewById(R.id.banner);
        mHorizontalListView = (HorizontalListView) layout.findViewById(R.id.hlv);

        loadProgressDialog.show();
        getVersionPersenter = new GetVersionPersenter(this);
        syssetPersenter = new SyssetPersenter(this);
        bookPresenter = new BookPresenter(this);
        bookPresenter.getFiltrateBooks(new MallBookRequest(index, size, String.valueOf(1)));
        bookPresenter.getSubjects();

        // app: Android ，平板：AndroidHD
        String apptype = "Android";
        GetVersionRequest getVersionRequest = new GetVersionRequest(apptype);
        syssetPersenter.getSysset(getVersionRequest);
        getVersionPersenter.getVersion(getVersionRequest);

        mAdapter = new HorizontalAdapter(subjects, getActivity());
        mHorizontalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                SubjectResponse subjectResponse = (SubjectResponse) adapterView.getItemAtPosition(i);
                intent = new Intent(getContext(), BookMarketActivity.class);
                intent.putExtra("subjectid", subjectResponse.getId());
                intent.putExtra("name", subjectResponse.getName());
                startActivity(intent);
            }
        });

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Book book = (Book) adapter.getItem(position);
                Log.d("id", books.get(position).getId() + "");
                Intent intent = new Intent(getContext(), BookDetialActivity.class);
                intent.putExtra("id", book.getId());
                startActivity(intent);
            }
        });
        View footerView = getFooterView(0, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saoMiao();
            }
        });
        adapter.addFooterView(footerView, 0);

    }

    private View getFooterView(int type, View.OnClickListener listener) {
        View view = getLayoutInflater().inflate(R.layout.book_footer, (ViewGroup) recyclerView.getParent(), false);
        if (type == 1) {
            ImageView imageView = view.findViewById(R.id.foot_img);
        }
        view.setOnClickListener(listener);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            index = 1;
                            refreshLayout.finishRefresh();
                        } catch (JsonSyntaxException e) {
                            UIUtils.showToast("数据加载异常");
                            e.printStackTrace();
                        }
                    }
                }, 2000);
            }
        });
        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                index++;
                mainPersenter.getMyBooks(new BookRequest(index, size));
                refreshlayout.finishLoadmoreWithNoMoreData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            index = 1;
                            books.clear();
                            adapter.replaceData(books);
                            mainPersenter.getMyBooks(new BookRequest(index, size));
                            refreshLayout.finishRefresh();
                        } catch (JsonSyntaxException e) {
                            UIUtils.showToast("数据加载异常");
                            e.printStackTrace();
                        }
                    }
                }, 2000);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        books.clear();
        index = 1;
        mainPersenter.getMyBooks(new BookRequest(index, size));
        mainPersenter.getHomeBanners();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.saomiao_img:
                saoMiao();
                break;
            default:
                break;
        }
    }

    private void saoMiao() {
        Intent intent = new Intent(getActivity(), CaptureActivity.class);

        /*ZxingConfig是配置类
         *可以设置是否显示底部布局，闪光灯，相册，
         * 是否播放提示音  震动
         * 设置扫描框颜色等
         * 也可以不传这个参数
         * */
        ZxingConfig config = new ZxingConfig();
        config.setPlayBeep(true);//是否播放扫描声音 默认为true
        config.setShake(true);//是否震动  默认为true
        intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
        startActivityForResult(intent, REQUEST_CODE_SCAN);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                if (content.contains("authorizeCardId") && content.contains("bookid")) {
                    Intent intent = new Intent(getContext(), SaoMiaoBookActivity.class);
                    intent.putExtra("content", content);
                    startActivity(intent);
                    Toast.makeText(getActivity(), "扫描结果" + content, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), "扫描格式不对，请确认", Toast.LENGTH_SHORT).show();
                }

            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s != null && s.toString().equals("0")) {
            mTabBar.showBadge(0, "" + 0, true);
            mTabBar.hideBadge(0);
            return;
        }
        if (s.toString().equals("")) {
            mTabBar.showBadge(0, "" + 0, true);
            return;
        }
        int count = Integer.parseInt(s.toString());
        if (mTabBar != null)
            mTabBar.showBadge(0, count + "", true);
    }

    @Override
    public void showMyBooks(Extra extra, ArrayList<Book> books) {
        this.books.addAll(books);
        adapter.replaceData(this.books);
    }

    @Override
    public void showBanners(ArrayList<BannerResponse> list) {
        int size = list.size();
        bannerResponses.clear();
        bannerResponses.addAll(list);
        String[] images = new String[size];
        for (int i = 0; i < list.size(); i++) {
            images[i] = list.get(i).getImg();
        }
        banner.setImages(Arrays.asList(images)).setImageLoader(new GlideImageLoader()).start();
        //设置点击事件，下标是从0开始
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if (bannerResponses.get(position).getType().equals("book")) {
                    Intent intent = new Intent(getContext(), BookDetialActivity.class);
                    intent.putExtra("id", bannerResponses.get(position).getMetadata().getId());
                    getContext().startActivity(intent);
                } else if (bannerResponses.get(position).getType().equals("h5")) {
                    if (!bannerResponses.get(position).getMetadata().getUrl().equals("")) {
                        Intent intent = new Intent(getContext(), FindwebViewActivity.class);
                        intent.putExtra("url", bannerResponses.get(position).getMetadata().getUrl());
                        getContext().startActivity(intent);
                    }
                } else {
                    Intent intent = new Intent(getContext(), BookMarketActivity.class);
                    intent.putExtra("cateid", bannerResponses.get(position).getMetadata().getId());
                    intent.putExtra("name", bannerResponses.get(position).getMetadata().getTitle());
                    getContext().startActivity(intent);
                }
            }
        });
    }

    @Override
    public void showSysset(SysSetting sysSetting) {
        mallmode = sysSetting.getData().isMallmode();
        SharedPreferencesUtils.setParam(getActivity(),"mallmode",mallmode);
        new Handler().postDelayed(new Runnable() {
            public void run() {
                if (mallmode) {
                    MineFragment.setViewVisible(true);
                }
            }
        }, 100);

    }

    @Override
    public void showGetVersion(Result<VersionResponse> responseResult) {
        if (!StringUtils.isNullOrEmpty(responseResult.getData().getPkgurl())){
            DetectionUpdate.checkApp(responseResult,getActivity(),"");
        }

    }


    @Override
    public void ShowError(Throwable throwable) {
        Toast.makeText(getContext(), ErrorUtils.showError(throwable), Toast.LENGTH_SHORT).show();
        if (MProgressDialog.isShowing()) {
            MProgressDialog.dismissProgress();
        }
    }

    @Override
    public void showMallBooks(ArrayList<Book> list) {
        loadProgressDialog.dismiss();
    }

    @Override
    public void getGrades(ArrayList<SubjectResponse> list) {
        loadProgressDialog.dismiss();
    }

    @Override
    public void getSubjects(ArrayList<SubjectResponse> list) {
        loadProgressDialog.dismiss();
        subjects.clear();
        subjects.addAll(list);
        mHorizontalListView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void showError(Throwable throwable) {
        loadProgressDialog.dismiss();
        Toast.makeText(getActivity(), ErrorUtils.showError(throwable), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showRegions(ArrayList<Province> province) {

    }

}
